package com.dwx.guli.service.trade.controller.api;

import com.dwx.guli.common.util.RandomUtils;
import com.dwx.guli.common.util.StreamUtils;
import com.dwx.guli.service.base.exception.GuliException;
import com.dwx.guli.service.base.result.R;
import com.dwx.guli.service.base.result.ResultCodeEnum;
import com.dwx.guli.service.trade.entity.Order;
import com.dwx.guli.service.trade.service.OrderService;
import com.dwx.guli.service.trade.service.WeixinPayService;
import com.dwx.guli.service.trade.util.WeixinPayProperties;
import com.github.wxpay.sdk.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags = "微信支付")
@CrossOrigin
@RestController
@RequestMapping("/api/trade/weixin-pay")
public class ApiWeixinPayController {
    @Autowired
    private WeixinPayProperties weixinPayProperties;
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private OrderService orderService;
    @ApiOperation("生成二维人码")
    @GetMapping("create-native/{orderNo}")
    public R createNative(@PathVariable("orderNo") String orderNo, HttpServletRequest request){
        String remoteAddr = request.getRemoteAddr();
        Map<String, Object> map = weixinPayService.createNative(orderNo, remoteAddr);
        return R.ok().data(map);
    }
    @PostMapping("callback/notify")
    public String wxNotify(HttpServletRequest request){
        log.info("微信发送的回调");
        try {
            ServletInputStream inputStream = request.getInputStream();
            String notifyXml = StreamUtils.inputStream2String(inputStream, "utf-8");
            log.info("notifyXml = " + notifyXml);
            if(WXPayUtil.isSignatureValid(notifyXml,weixinPayProperties.getPartnerKey())){
                log.info("验签成功");

                Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyXml);
                if("SUCCESS".equals(notifyMap.get("return_code"))&&"SUCCESS".equals(notifyMap.get("result_code"))){
                    String orderNo = notifyMap.get("out_trade_no");
                    Order order = orderService.getOrderByOrderNo(orderNo);
                    if(order!=null&&order.getTotalFee()==Long.parseLong(notifyMap.get("total_fee"))){
                        synchronized (this){
                            if(order.getStatus()==0){
                                orderService.updateOrderStatus(notifyMap);
                            }
                        }
                        Map<String ,String> resultMap=new HashMap<>();
                        resultMap.put("return_code","SUCCESS");
                        resultMap.put("return_msg","OK");
                        String returnXml = WXPayUtil.mapToXml(resultMap);
                        log.info("支付成功，已应答");
                        return returnXml;
                    }
                }
            }
            Map<String ,String> resultMap=new HashMap<>();
            resultMap.put("return_code","FAIL");
            resultMap.put("return_msg","ERROR");
            String returnXml = WXPayUtil.mapToXml(resultMap);
            return returnXml;
        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
        }
    }
}
